'use strict'

import { app, protocol, BrowserWindow, Menu } from 'electron'
const { session } = require('electron')
const path = require('path')
const ipcMain = require('electron').ipcMain;
const dialog = require('electron').dialog;
const Tray = require('electron').Tray;
// const { autoUpdater } = require("electron-updater")
import {
    createProtocol,
    /* installVueDevtools */
} from 'vue-cli-plugin-electron-builder/lib'

const isDevelopment = process.env.NODE_ENV !== 'production'
// 发送消息给渲染线程
function sendStatusToWindow(status, params) {
    win.webContents.send(status, params)
}
// autoUpdater.autoDownload = true // 关闭自动更新
// autoUpdater.autoInstallOnAppQuit = true // APP退出的时候自动安装
// autoUpdater.on('checking-for-update', () => {
//     sendStatusToWindow('Checking for update...,send guest progress')
// })
// autoUpdater.on('update-available', (info) => {
//     // 可以更新版本
//     sendStatusToWindow('autoUpdater-canUpdate', info)
// })
// // autoUpdater.on('update-not-available', (info) => {
// //   // 不能够更新
// // })
// autoUpdater.on('error', (err) => {
//     // 更新错误
//     sendStatusToWindow('autoUpdater-error', err)
// })
// autoUpdater.on('download-progress', (progressObj) => {
//     // 正在下载的下载进度
//     sendStatusToWindow('autoUpdater-progress', progressObj)
// })
// autoUpdater.on('update-downloaded', (info) => {
//     // 下载完成
//     sendStatusToWindow('autoUpdater-downloaded')
// })

ipcMain.on("rootFilePath", (event) => {
    win.webContents.send("rootFilePath", path.resolve(__dirname));
});
ipcMain.on("openFile", (event, filepath) => {


    dialog.showOpenDialog(win, {
        properties: ['openDirectory'],
        defaultPath: filepath ? filepath : path.resolve(__dirname)
    }).then(result => {
        if (!result.canceled) {
            console.log(result.filePaths[0]); // 选择的文件夹路径
            win.webContents.send("setFilePath", result.filePaths[0]);
        }
    }).catch(err => {
        console.error(err);
    });



});
ipcMain.on("exit-app", () => {
    app.exit();
});
var appTray = null;
let win;
let template = [{
        label: '携客云打标系统V1.0'
    },
    {
        label: '客服微信:17606035024'
    },
    {
        label: '重新加载',
        accelerator: 'CmdOrCtrl+R',
        role: 'forcereload'
    },
    {
        label: '设置',
        submenu: [{
            label: '最小化',
            accelerator: 'CmdOrCtrl+M',
            role: 'minimize'
        }, {
            label: '关闭',
            accelerator: 'CmdOrCtrl+W',
            role: 'close'
        }, {
            type: 'separator'
        }]
    }
];
let trayMenuTemplate = [{
        label: '刷新',
        role: 'forcereload'

    },
    {
        label: '退出',
        click: function() {
            app.exit();
        }
    }
];



// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])

function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({
        width: 800,
        height: 600,
        icon: __dirname + '/images/desktopapp.ico',
        webPreferences: {
            nodeIntegration: true,
            show: false,
            maximizable: true,
            webviewTag: true,
            javascript: true,
            nodeIntegrationInWorker: true,
            contextIsolation: false,
            plugins: true,
            webSecurity: true

        }
    });
    let menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu);
    let contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
    //设置此托盘图标的悬停提示内容
    appTray = new Tray(path.join(app.getAppPath(), 'desktopapp.ico'));
    appTray.setToolTip('携客云打标系统');

    appTray.setContextMenu(contextMenu);


    appTray.on('click', function() {
        win.maximize();

    });


    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        //win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        win.loadURL("https://dabiao.roctc.com")
        if (process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        // win.loadURL('app://./index.html')
        // win.loadURL("https://dabiao.roctc.com")
        win.webContents.openDevTools()

    }

    win.on("close", (e) => {

        e.preventDefault();
        dialog.showMessageBox(win, {
            type: "info",
            title: "是否退出",
            message: "是否退出打标系统",
            defaultId: 0,
            buttons: [
                '最小化', '直接退出'
            ]
        }).then(result => {

            if (result.response === 0) {
                e.preventDefault();
                win.minimize();
            } else {
                app.exit();
            }
        });
    });
    win.on('closed', () => {
        win = null
    });
    win.maximize()
    win.show()
};

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow()
    }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        // Devtools extensions are broken in Electron 6.0.0 and greater
        // See https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/378 for more info
        // Electron will not launch with Devtools extensions installed on Windows 10 with dark mode
        // If you are not using Windows 10 dark mode, you may uncomment these lines
        // In addition, if the linked issue is closed, you can upgrade electron and uncomment these lines
        // try {
        //   await installVueDevtools()
        // } catch (e) {
        //   console.error('Vue Devtools failed to install:', e.toString())
        // }

    }
    createWindow();

    setTimeout(() => {
        // 检测是否有更新
        // autoUpdater.checkForUpdates()
    }, 1500);


})
app.setAppUserModelId("多店聊聊-shopee助手")
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', data => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}